package com.jsgt.greekfire.ui.mine


import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.AppConfig
import com.fhx.core.base.BaseFragment
import com.fhx.core.goToActivity
import com.fhx.core.utils.*
import com.jsgt.greekfire.*
import com.jsgt.greekfire.bean.AssetsBean
import com.jsgt.greekfire.bean.UpdateBean
import com.jsgt.greekfire.bean.UserBean
import com.jsgt.greekfire.common.util.NetDataManager
import com.jsgt.greekfire.event.*
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.factory.WalletViewModelFactory
import com.jsgt.greekfire.ui.home.entrance.EntranceActivity
import com.jsgt.greekfire.ui.main.updatedialog.UpdateDialogFragment
import com.jsgt.greekfire.ui.mine.coindetail.CoinDetailActivity
import com.jsgt.greekfire.ui.mine.sermoncommunity.SermonCommunityActivity
import com.jsgt.greekfire.ui.mine.user.address.AddressActivity
import com.jsgt.greekfire.ui.mine.user.backupwalletword.BackUpWalletWordActivity
import com.jsgt.greekfire.ui.mine.user.changesecuritypwd.ChangeSecurityPwdActivity
import com.jsgt.greekfire.ui.mine.user.changetradingpwd.ChangeTradingPwdActivity
import com.jsgt.greekfire.ui.mine.user.messagelist.MessageListActivity
import com.jsgt.greekfire.ui.mine.user.securityset.SecuritySetActivity
import com.jsgt.greekfire.viewmodel.UserViewModel
import com.jsgt.greekfire.viewmodel.WalletViewModel1
import kotlinx.android.synthetic.main.fragment_mine1.*
import kotlinx.android.synthetic.main.view_mine_header.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 资产
 */
class MineFragment : BaseFragment(), View.OnClickListener {


    // 定义保存的文件的名称
    private val languageName = "sharedfile"


    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }
    private val walletViewModel1: WalletViewModel1 by lazy {
        ViewModelProvider(
            this,
            WalletViewModelFactory()
        ).get(WalletViewModel1::class.java)
    }
    private var pwdDialog: Dialog? = null

    private var isRefresh = true

    private var gfcPrice: Double = 0.0

    private var gftPrice: Double = 0.0

    private var usdtPrice: Double = 0.0

    private var version: String? = null

    private var updateBean: UpdateBean? = null


    var updateDialogFragment: UpdateDialogFragment? = null

    companion object {
        const val REQUEST_CODE = 1011
    }

    override fun getLayoutId(): Int = R.layout.fragment_mine1

    override fun onResume() {
        super.onResume()
        loadData()
        userViewModel.userInfo()
        LogUtils.error("onResume")
    }

    override fun onStart() {
        super.onStart()
        LogUtils.error("onStart")
    }

    override fun main() {

        Sermon_community.setOnClickListener(this)
        mine_wallet_management.setOnClickListener(this)
        mine_wallet_backup.setOnClickListener(this)
        address_book.setOnClickListener(this)
        mine_view_language.setOnClickListener(this)
        mine_msg_center.setOnClickListener(this)
        miner_change_trading_pwd.setOnClickListener(this)
        mine_change_security_pwd.setOnClickListener(this)
        mine_security_set.setOnClickListener(this)
        mine_exit.setOnClickListener(this)
        mine_check_version.setOnClickListener(this)

        userViewModel.activityTransferList()

        //币种的返回数据
        NetDataManager.getUserAssets()

        mine.setOnRefreshListener {
            isRefresh = true
            loadData()
            NetDataManager.getWalletInfo()
            NetDataManager.getUserAssets()
            //查询币种价格
            userViewModel.getPrice()
        }
        //异常
        if (NetDataManager.assetsList.size > 3) {
            gfc_dollar.text = PriceFormatUtil.format(NetDataManager.assetsList[0].assetBalance, 4)
            dollar_usdt.text = PriceFormatUtil.format(NetDataManager.assetsList[1].assetBalance, 4)
            gft_dollar.text = PriceFormatUtil.format(NetDataManager.assetsList[2].assetBalance, 4)

        if (NetDataManager.assetsList.size < 3){
            return
        }

            gfc_money.text = "$" + PriceFormatUtil.format(
                (NetDataManager.assetsList[0].assetBalance!! + NetDataManager.assetsList[0].assetFrozen!!) * gfcPrice,
                4
            )
            usdt_money.text = "$" + PriceFormatUtil.format(
                (NetDataManager.assetsList[1].assetBalance!! + NetDataManager.assetsList[1].assetFrozen!!) * usdtPrice,
                4
            )
            gft_money.text = "$" + PriceFormatUtil.format(
                (NetDataManager.assetsList[2].assetBalance!! + NetDataManager.assetsList[2].assetFrozen!!) * gftPrice,
                4
            )

            val assets_money1 =
                (NetDataManager.assetsList[0].assetBalance!! + NetDataManager.assetsList[0].assetFrozen!!).times(
                    gfcPrice
                )
            val assets_money2 =
                (NetDataManager.assetsList[1].assetBalance!! + NetDataManager.assetsList[1].assetFrozen!!).times(
                    usdtPrice
                )
            val assets_money3 =
                (NetDataManager.assetsList[2].assetBalance!! + NetDataManager.assetsList[2].assetFrozen!!).times(
                    gftPrice
                )

            val sum = assets_money1 + assets_money2 + assets_money3
            total_assets_tv.text =
                "$" + PriceFormatUtil.format(sum, 4)
            total_assets_tv_cny.text = "≈ ${PriceFormatUtil.format(sum * 7, 2)}CNY"

            loadData()
            //查询币种价格
            userViewModel.getPrice()
            userViewModel.getPrice.observe(activity!!, Observer {
                gfcPrice = it.gfcPrice
                usdtPrice = it.usdtPrice
                gftPrice = if (App.context.gftPrice == 0.0) it.gfcPrice else App.context.gftPrice
                onAssetsEvent(null)
            })


            gfc_name.setOnClickListener {
                CoinDetailActivity.start(context!!, NetDataManager.assetsList[0], gfcPrice)
            }

            usdt_name.setOnClickListener {
                CoinDetailActivity.start(context!!, NetDataManager.assetsList[1], usdtPrice)
            }

            gft_name.setOnClickListener {
                CoinDetailActivity.start(context!!, NetDataManager.assetsList[2], gftPrice)
            }


            balance_view_tv.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked) {
                    total_assets_tv.text = "****"
                    total_assets_tv_cny.text = "***"
                    gfc_dollar.text = "***"
                    gfc_money.text = "***"
                    dollar_usdt.text = "***"
                    usdt_money.text = "***"
                    gft_dollar.text = "***"
                    gft_money.text = "***"
                    SharePreferencesUtil.saveBoolean(activity!!, SUM_IS_VIEW, true)

                } else {

                    gfc_dollar.text =
                        PriceFormatUtil.format(NetDataManager.assetsList[0].assetBalance, 4)
                    dollar_usdt.text =
                        PriceFormatUtil.format(NetDataManager.assetsList[1].assetBalance, 4)
                    gft_dollar.text =
                        PriceFormatUtil.format(NetDataManager.assetsList[2].assetBalance, 4)

                    gfc_money.text = "$" + PriceFormatUtil.format(
                        (NetDataManager.assetsList[0].assetBalance!! + NetDataManager.assetsList[0].assetFrozen!!) * gfcPrice,
                        4
                    )
                    usdt_money.text = "$" + PriceFormatUtil.format(
                        (NetDataManager.assetsList[1].assetBalance!! + NetDataManager.assetsList[1].assetFrozen!!) * usdtPrice,
                        4
                    )
                    gft_money.text = "$" + PriceFormatUtil.format(
                        (NetDataManager.assetsList[2].assetBalance!! + NetDataManager.assetsList[2].assetFrozen!!) * gftPrice,
                        4
                    )

                    val assets_money1 =
                        (NetDataManager.assetsList[0].assetBalance!! + NetDataManager.assetsList[0].assetFrozen!!).times(
                            gfcPrice
                        )
                    val assets_money2 =
                        (NetDataManager.assetsList[1].assetBalance!! + NetDataManager.assetsList[1].assetFrozen!!).times(
                            usdtPrice
                        )
                    val assets_money3 =
                        (NetDataManager.assetsList[2].assetBalance!! + NetDataManager.assetsList[2].assetFrozen!!).times(
                            gftPrice
                        )

                    val sum = assets_money1 + assets_money2 + assets_money3
                    total_assets_tv.text =
                        "$" + PriceFormatUtil.format(sum, 4)
                    total_assets_tv_cny.text = "≈ ${PriceFormatUtil.format(sum * 7, 2)}CNY"

                    SharePreferencesUtil.saveBoolean(activity!!, SUM_IS_VIEW, false)
                }
            }


            userViewModel.activityTransferList.observe(activity!!, Observer {
                mine.isRefreshing = false
            })

            userViewModel.getPrice.observe(activity!!, Observer {
                mine.isRefreshing = false

            })

        }


        showProgress(true)
        NetDataManager.getWalletInfo()
        userViewModel.userInfoLiveData.observe(activity!!, Observer {
            mine.isRefreshing = false
            UserBean.instance.mobile = it.mobile
            UserBean.instance.email = it.email
        })

        //备份钱包的判断
        walletViewModel1.checkSecurityLiveData.observe(activity!!, Observer {
            mine.isRefreshing = false
            //showToast("密码验证成功")
            showProgress(false)
            pwdDialog?.dismiss()
            pwdDialog = null
            goToActivity<BackUpWalletWordActivity>()

        })
        walletViewModel1.errorLiveData.observe(activity!!, Observer {
            mine.isRefreshing = false
            showProgress(false)
        })
        userViewModel.errorLiveData.observe(activity!!, Observer {
            mine.isRefreshing = false
            showProgress(false)
        })

        userViewModel.versionUpdateLiveData.observe(this, Observer {
            showProgress(false)
            version = it.Android!!.version.toString()
            updateBean = it
            showUploadDialog()
        })

//        when (SharePreferencesUtil.getString(activity!!, languageName, "")) {

//            "cn" -> {
//                simplified_chinese.text = getString(R.string.Simplified_Chinese)
//            }
//            "en" -> {
//                simplified_chinese.text = "English"
//
//            }
//        }

    }

    fun loadData() {

        if (LOGIN_STATUS) {
            NetDataManager.getUSTDPrice()
            userViewModel.userInfo()
        } else {
            mine.isRefreshing = false
        }


    }

    override fun onClick(v: View?) {
        if (isFastClick()) {
            return
        }

        when (v?.id) {
            //布道社区
            R.id.Sermon_community -> {
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(activity!!, getString(R.string.account_no_activation))
                } else {
//                goToActivity<MinersPurseActivity>()
                    goToActivity<SermonCommunityActivity>()

                }
            }

            //钱包管理
            R.id.mine_wallet_management -> {
                goToActivity<EntranceActivity>()
            }
            //钱包备份
            R.id.mine_wallet_backup -> {
//                goToActivity<EntranceActivity>()
                showInputPwdDialog()
            }
            //地址簿
            R.id.address_book -> {
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(activity!!, getString(R.string.account_no_activation))
                } else {
                    goToActivity<AddressActivity>()
                }
            }
            //显示语言
            R.id.mine_view_language -> {
                ToastUtils.show(activity!!, "暂未开放")
//                goToActivity<LanguageActivity>()
            }
            //通知中心
            R.id.mine_msg_center -> {
                goToActivity<MessageListActivity>()
            }

            // 修改交易密码
            R.id.miner_change_trading_pwd -> {
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(activity!!, getString(R.string.account_no_activation))
                } else {
                    if (TextUtils.isEmpty(UserBean.instance.mobile)) {
                        ToastUtils.show(activity!!, "请先绑定手机")
                    } else {
                        goToActivity<ChangeTradingPwdActivity>()
                    }
                }
            }
            // 修改钱包密码
            R.id.mine_change_security_pwd -> {
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(activity!!, getString(R.string.account_no_activation))
                } else {
                    goToActivity<ChangeSecurityPwdActivity>()

                }
            }
            // 安全设置
            R.id.mine_security_set -> {
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(activity!!, getString(R.string.account_no_activation))
                } else {
                    goToActivity<SecuritySetActivity>()
                }
            }
            //推出
            R.id.mine_exit -> exit()

            //检查更新
            R.id.mine_check_version -> {
                showProgress(true)
                userViewModel.getAppVersion()
            }
        }
    }

    private fun showUploadDialog() {
        if (AppConfig.getVersion()!! < version!!) {
            val bundle = Bundle()
            bundle.putParcelable("bean", updateBean)
            updateDialogFragment = UpdateDialogFragment()
            updateDialogFragment!!.arguments = bundle
            updateDialogFragment!!.show(childFragmentManager, "updateFragment")
        } else {

            val contentView =
                layoutInflater.inflate(R.layout.dialog_check_view, null, false)
            pwdDialog = DialogUtil.show(activity!!, contentView)
            pwdDialog?.setOnDismissListener {
                pwdDialog = null
            }
            pwdDialog?.setCanceledOnTouchOutside(true)
            pwdDialog?.setCancelable(true)
            pwdDialog?.show()

            val item_version = contentView.findViewById<TextView>(R.id.item_version)

            item_version.text = "当前版本号" + AppConfig.getVersion()

            contentView.findViewById<TextView>(R.id.pop_sure).setOnClickListener {
                pwdDialog?.dismiss()
                showProgress(false)
            }
        }
    }

    private fun exit() {
        App.context.logout()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        userViewModel.getPrice()
        NetDataManager.getUserAssets()

        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            IS_ACTIVATION = 2
            userViewModel.activityTransferList()
        }
    }

    private fun showInputPwdDialog() {
        val contentView = layoutInflater.inflate(R.layout.dialog_input_wallet_pwd, null, false)
        pwdDialog = DialogUtil.show(activity!!, contentView)
        pwdDialog?.setOnDismissListener {
            pwdDialog = null
        }
        pwdDialog?.setCanceledOnTouchOutside(true)
        pwdDialog?.setCancelable(true)
        pwdDialog?.show()


        contentView.findViewById<TextView>(R.id.check_pwd_tv_cancel).setOnClickListener {
            pwdDialog?.dismiss()
        }

        contentView.findViewById<TextView>(R.id.check_pwd_tv).setOnClickListener {
            val pwd = contentView.findViewById<EditText>(R.id.pwd_et).text.toString().trim()
            if (TextUtils.isEmpty(pwd)) {
                showToast("密码不能为空")
            } else {
                //服务端验证
                walletViewModel1.checkWalletSecurityPwd(pwd)
                pwdDialog?.dismiss()
                showProgress(true)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onWalletInfoEvent(e: WalletInfoEvent) {
        showProgress(false)
        val info = NetDataManager.walletInfo ?: return
        if (info.walletLevel == 0) {
            imv_super_note.visibility = View.GONE
        } else {
            imv_super_note.visibility = View.VISIBLE
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGFTPriceEvent(e: GFTPriceEvent) {
        gftPrice = e.price
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            loadData()
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAssetsEvent(e: AssetsEvent?) {
//        NetDataManager.getUserAssets()

        if (SharePreferencesUtil.getBoolean(activity!!, SUM_IS_VIEW, false)) {
            balance_view_tv.isChecked = true
            total_assets_tv.text = "****"
            total_assets_tv_cny.text = "***"
            gfc_dollar.text = "***"
            gfc_money.text = "***"
            dollar_usdt.text = "***"
            usdt_money.text = "***"
            gft_dollar.text = "***"
            gft_money.text = "***"

        } else {
            if (NetDataManager.assetsList.size < 3) {
                return
            }
            gfc_dollar.text = PriceFormatUtil.format(NetDataManager.assetsList[0].assetBalance, 4)
            dollar_usdt.text = PriceFormatUtil.format(NetDataManager.assetsList[1].assetBalance, 4)
            gft_dollar.text = PriceFormatUtil.format(NetDataManager.assetsList[2].assetBalance, 4)

            gfc_money.text = "$" + PriceFormatUtil.format(
                (NetDataManager.assetsList[0].assetBalance!! + NetDataManager.assetsList[0].assetFrozen!!) * gfcPrice,
                4
            )
            usdt_money.text = "$" + PriceFormatUtil.format(
                (NetDataManager.assetsList[1].assetBalance!! + NetDataManager.assetsList[1].assetFrozen!!) * usdtPrice,
                4
            )
            gft_money.text = "$" + PriceFormatUtil.format(
                (NetDataManager.assetsList[2].assetBalance!! + NetDataManager.assetsList[2].assetFrozen!!) * gftPrice,
                4
            )

            val assets_money1 =
                (NetDataManager.assetsList[0].assetBalance!! + NetDataManager.assetsList[0].assetFrozen!!).times(
                    gfcPrice
                )
            val assets_money2 =
                (NetDataManager.assetsList[1].assetBalance!! + NetDataManager.assetsList[1].assetFrozen!!).times(
                    usdtPrice
                )
            val assets_money3 =
                (NetDataManager.assetsList[2].assetBalance!! + NetDataManager.assetsList[2].assetFrozen!!).times(
                    gftPrice
                )

            val sum = assets_money1 + assets_money2 + assets_money3
            total_assets_tv.text =
                "$" + PriceFormatUtil.format(sum, 4)
            total_assets_tv_cny.text = "≈ ${PriceFormatUtil.format(sum * 7, 2)}CNY"


            balance_view_tv.isChecked = false
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUSDTPriceEvent(e: USDTPriceEvent) {
    }

    private fun filterList(list: List<AssetsBean>): List<AssetsBean> = list.filter {
        it.assetGuid!!.toInt() < 4
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTransferEvent(e: TransferEvent) {
        loadData()
    }

    override fun onDestroy() {
        super.onDestroy()
        pwdDialog = null
    }
}